package org.Exm_1;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        PurchaseSystem system = new PurchaseSystem();
        Scanner scanner = new Scanner(System.in);

        try {
            System.out.println("当前工作目录: " + Paths.get("").toAbsolutePath());
            system.loadProducts();
            System.out.println("系统初始化完成，商品已加载");
        } catch (IOException e) {
            System.err.println("初始化失败: " + e.getMessage());
            System.err.println("请确认：");
            System.err.println("1. 程序有文件读写权限");
            System.err.println("2. 磁盘空间充足");
            return;
        }

        while (true) {
            System.out.println("\n1. 查看商品列表");
            System.out.println("2. 购买商品");
            System.out.println("3. 退出");
            System.out.print("请选择: ");

            String choice = scanner.nextLine();
            switch (choice) {
                case "1":
                    system.listProducts();
                    break;
                case "2":
                    purchaseMenu(system, scanner);
                    break;
                case "3":
                    System.out.println("谢谢使用!");
                    return;
                default:
                    System.out.println("无效选择");
            }
        }
    }

    private static void purchaseMenu(PurchaseSystem system, Scanner scanner) {
        try {
            System.out.print("输入用户ID: ");
            String userId = scanner.nextLine();

            System.out.print("输入商品ID: ");
            int productId = Integer.parseInt(scanner.nextLine());

            System.out.print("输入购买数量: ");
            int quantity = Integer.parseInt(scanner.nextLine());

            if (!system.makePurchase(userId, productId, quantity)) {
                System.out.println("购买失败，请检查错误信息");
            }
        } catch (NumberFormatException e) {
            System.out.println("输入错误: 请输入有效的数字");
        }
    }
}